package com.simple.datax.flow.processor;

import java.util.List;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.simple.datax.api.MessageService;
import com.simple.datax.flow.constants.ProcessResultConstants;
import com.simple.datax.flow.constants.TaskActivityConstants;
import com.simple.datax.flow.convertor.Convertor;
import com.simple.datax.flow.dao.ibatis.model.FlowActivityInstance;
import com.simple.datax.flow.generator.MessageGenerator;
import com.simple.datax.flow.message.BaseEcMessage;
import com.simple.datax.flow.message.EcFlowMessage;
import com.simple.datax.flow.message.EcFlowRespMessage;
import com.simple.datax.flow.preprocessor.PreProcessorAdaptor;
import com.simple.datax.flow.preprocessor.PreProcessorService;
import com.simple.datax.flow.service.TaskActivityManager;
import com.simple.datax.flow.service.TaskManager;
import com.simple.datax.flow.service.TaskMessageManager;
import com.simple.datax.flow.util.FailMessageUtil;

/** 
 * @Title: BaseMessageProcessor.java 
 * @Package com.simple.datax.flow.processor 
 * @Description: TODO(添加描述) 
 * @author tonney 
 * @date 2013-3-4 下午07:53:32 
 * @version V1.0 
 */
public abstract class BaseMessageProcessor {

	protected MessageService routerMessageService;
	
	protected Convertor messageConvertor;
	
	protected TaskActivityManager taskActivityManager;
	
	private TaskManager taskManager = null;

	protected PreProcessorAdaptor preProcessorAdaptor = null;
	
	private TaskMessageManager taskMessageManager;

	public void setPreProcessorAdaptor(PreProcessorAdaptor preProcessorAdaptor) {
		this.preProcessorAdaptor = preProcessorAdaptor;
	}

	public void setTaskManager(TaskManager taskManager) {
		this.taskManager = taskManager;
	}

	public void setTaskMessageManager(TaskMessageManager taskMessageManager) {
		this.taskMessageManager = taskMessageManager;
	}

	public void setTaskActivityManager(TaskActivityManager taskActivityManager) {
		this.taskActivityManager = taskActivityManager;
	}

	public void setMessageConvertor(Convertor messageConvertor) {
		this.messageConvertor = messageConvertor;
	}

	public void setRouterMessageService(MessageService routerMessageService) {
		this.routerMessageService = routerMessageService;
	}
	
	public Logger log = LoggerFactory.getLogger(this.getClass());
	
	/**
	 * 处理本次活动预处理后生成的活动集，如果活动集中有一个失败则本次任务中对应的活动失败
	 * @param messageList  预处理后生成的活动集
	 * @param xmlMessageList  活动集处理后的XML报文字符串
	 * @param activityInstanceList  活动集信息，用于保存至数据库和缓存
	 * @return
	 */
	public int processActivitys(List<BaseEcMessage> messageList,List<String> xmlMessageList,List<FlowActivityInstance> activityInstanceList){
		int result = ProcessResultConstants.STATUS_SUCCESS;
		String flowid = null;
		String taskid = null;
		List<String> activityNoList = null;
//		String activityNo = null;
		FlowActivityInstance activityInstance = null;
		PreProcessorService preProcessor = null;
		String xmlMessage = null;
		try{
			if (messageList != null && messageList.size() > 0) {
				EcFlowMessage ecMessage = null;
				for (BaseEcMessage baseMessage : messageList) {
					try{
						ecMessage = (EcFlowMessage)baseMessage;
						flowid = ecMessage.getFlowMessageBody().getFlowId();
						taskid = ecMessage.getFlowMessageBody().getTaskId();
						String userid = ecMessage.getFlowMessageBody().getUserId();
						activityNoList = ecMessage.getFlowMessageBody()
								.getActivityIdList();
						if (activityNoList != null
								&& activityNoList.size() >= 1) {
							for(String activityNo:activityNoList){
	//							activityNo = activityNoList.get(0);
								if (ecMessage.isValidActivityNo()) { // 走协议的活动号不需要校验，例如TCS企业过来后转换的任务
									result = taskManager.validateTaskid(flowid,
										taskid,userid);
								}
								if (result == ProcessResultConstants.STATUS_SUCCESS) {
									activityInstance = taskActivityManager
											.getFlowActivityInstance(flowid,
													activityNo);
									if (activityInstance != null) {
										if (ecMessage.isValidActivityNo()) { // 走协议的活动号不需要校验，例如TCS企业过来后转换的活动号
											result = taskActivityManager
													.validateActivity(ecMessage.getOrgSendId(),taskid,
															activityNo,
															activityInstance);
										}
										if (result == ProcessResultConstants.STATUS_SUCCESS) {
											result = taskActivityManager
													.editMessageByFlowidAndActivityNo(
															flowid, activityNo,
															ecMessage,
															activityInstance);
											if (result == ProcessResultConstants.STATUS_SUCCESS) {
												/***************************** 协议企业发送前预处理 BEGIN ******************************************/
												preProcessor = preProcessorAdaptor
														.getPreProcessorServiceByEcode(ecMessage
																.getFlowMessageHead()
																.getReceiverId());
												if (preProcessor != null) {
													result = preProcessor
															.sendPreProcessor(ecMessage);
												}
												/***************************** 协议企业发送前预处理 BEGIN ******************************************/
		
												if (result == ProcessResultConstants.STATUS_SUCCESS) {
	//												try {
													xmlMessage = messageConvertor
													.convert2StringXml(ecMessage);
													xmlMessageList.add(xmlMessage);
													// 记录任务处理结果到数据库，同时修改redis缓存记录
													// taskMessageManager.saveTaskMessage(activityInstance,ecMessage);//保存报文发送记录
													activityInstance
															.setTaskId(ecMessage
																	.getFlowMessageBody()
																	.getTaskId());
													activityInstance
															.setStatus(TaskActivityConstants.STATUS_SUCCESS);
													activityInstance
															.setDueResult("1");
													activityInstance
															.setMessageId(ecMessage
																	.getFlowMessageHead()
																	.getMessageId());
													activityInstanceList.add(activityInstance);
												} else { // 任务处理失败，修改任务状态
													log.warn("BaseMessageProcessor::processActivitys warn=>PreProcessor before Send failure");
													break;
												}
											} else {
												log.warn("BaseMessageProcessor::processActivitys warn=> Edit EcMessage failure");
												break;
											}
										}
									} else {
										result = ProcessResultConstants.STATUS_ACTIVITY_INVALID;
										log.warn("BaseMessageProcessor::processActivitys warn=> getFlowActivityInstance return null");
										break;
									}
								}
							}
						} else {
							result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
							log.error("BaseMessageProcessor::processActivitys warn=> No ActivityNo");
							break;
						}
					}catch(Exception e){
						result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
						log.error("BaseMessageProcessor::processActivitys Process Message Error=>"+e.toString());		
						break;
					}
				}
			} else {
				result = ProcessResultConstants.STATUS_RECV_PROCESS_EXCEPTION;
				log.error("BaseMessageProcessor::processActivitys warn=> Message PreProcess return null");
			}
		}catch(Exception e){
			result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
			log.error("BaseMessageProcessor::processActivity Error=>"+e.toString());		
		}
		return result;
	}
	
	/**
	 * 发送报文
	 * @param xmlMessageList
	 * @return
	 */
	public int sendXmlMessages(List<String> xmlMessageList){
		int result = ProcessResultConstants.STATUS_SUCCESS;
		try{
			if(xmlMessageList!=null){
				for(String xmlMessage:xmlMessageList){
					try{
						routerMessageService.service(xmlMessage);
						log.debug("send Message==>"+xmlMessage);
					}catch(Exception e){
						FailMessageUtil.addFailMessage(xmlMessage);
						log.error("BaseMessageProcessor::sendXmlMessages invoke router service error==>"
								+ e.toString());
					}
				}
			}
		}catch(Exception e){
			result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
			log.error("BaseMessageProcessor::sendXmlMessages error==>"
					+ e.toString());
		}
		return result;
	}

	/**
	 * 根据原始报文生成错误报文并发送
	 * @param orgFlowMessage
	 * @return
	 */
	public int sendFailMessages(EcFlowMessage orgFlowMessage,int failcode){
		int result = ProcessResultConstants.STATUS_SUCCESS;
		String xmlMessage = null;
		try{
			EcFlowRespMessage flowRespMsg = MessageGenerator
			.generatFailureRespMessage(orgFlowMessage, failcode);
			xmlMessage = messageConvertor
						.convert2StringXml(flowRespMsg);
			// 发送给路由处理模块
			try {
				routerMessageService.service(xmlMessage);
			} catch (Exception e) {
				FailMessageUtil.addFailMessage(xmlMessage);
				log.error("BaseMessageProcessor::sendFailMessages invoke router service error==>"
						+ e.toString());
			}
		}catch(Exception e){
			result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
			log.error("BaseMessageProcessor::sendFailMessages error==>"
					+ e.toString());
		}
		log.debug("send Fail Message==>"+xmlMessage);
		return result;
	}
	

	/**
	 * 修改数据库和缓存中活动状态信息
	 * @param activityInstanceList
	 * @return
	 */
	public int updateFlowActivitys(List<FlowActivityInstance> activityInstanceList){
		int result = ProcessResultConstants.STATUS_SUCCESS;
		try{
			if(activityInstanceList!=null){
				for(FlowActivityInstance activityInstance:activityInstanceList){
					taskActivityManager.saveFlowActivityInstance(activityInstance);
				}
			}
		}catch(Exception e){
			result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
			log.error("BaseMessageProcessor::updateFlowActivitys error==>"
					+ e.toString());
		}
		return result;
	}
	
}
